﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using sdamarketing.App_Code;

namespace sdamarketing.Account
{
    public partial class AccountDetails : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                if (!IsPostBack)
                {
                    try
                    {
                        if (Session["iduser"] == null || Session["username"] == null)
                        {
                            Response.Redirect("~/Default.aspx");
                        }

                        // AN Gi polnam text boxovite so infrmaciite na userot vo sesijata
                        DataSet user = ReturnDataSet.ReturSet("SELECT firstName, lastName, username, password, eMail, securityQuestion, securityAnswer,idSex,idEducation,idRegion,idAge,idSocialStructure,idNationality,idIncome,idLocality FROM Users WHERE idUser = '" + Session["idUser"].ToString() + "'");
                        UsernameTextBox.Enabled = false;
                        FirstNameTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[0].ToString();
                        LastNameTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[1].ToString();
                        UsernameTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[2].ToString();
                        //     PasswordTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[3].ToString();
                        //     PasswordConfTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[3].ToString();
                        EMailTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[4].ToString();
                        QuestionTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[5].ToString();
                        AnswerTextBox.Text = user.Tables["DataSet"].Rows[0].ItemArray[6].ToString();

                        DataSet Sex = ReturnDataSet.ReturSet("SELECT idSex, sex FROM Sex");
                        DropDownListSex.DataValueField = "idSex";
                        DropDownListSex.DataTextField = "sex";
                        DropDownListSex.DataSource = Sex;
                        DropDownListSex.DataBind();
                        DropDownListSex.Items.Insert(0, new ListItem("", ""));

                        DataSet Age = ReturnDataSet.ReturSet("SELECT idAge, fromAndTo FROM Age");
                        DropDownListAge.DataValueField = "idAge";
                        DropDownListAge.DataTextField = "fromAndTo";
                        DropDownListAge.DataSource = Age;
                        DropDownListAge.DataBind();
                        DropDownListAge.Items.Insert(0, new ListItem("", ""));

                        DataSet Education = ReturnDataSet.ReturSet("SELECT idEducation, education FROM Educations");
                        DropDownListEducation.DataValueField = "idEducation";
                        DropDownListEducation.DataTextField = "education";
                        DropDownListEducation.DataSource = Education;
                        DropDownListEducation.DataBind();
                        DropDownListEducation.Items.Insert(0, new ListItem("", ""));

                        DataSet Status = ReturnDataSet.ReturSet("SELECT idSocialStructure, status FROM SocialStructures");
                        DropDownListStructure.DataValueField = "idSocialStructure";
                        DropDownListStructure.DataTextField = "status";
                        DropDownListStructure.DataSource = Status;
                        DropDownListStructure.DataBind();
                        DropDownListStructure.Items.Insert(0, new ListItem("", ""));

                        DataSet Nacionalost = ReturnDataSet.ReturSet("SELECT idNacionalnost,Nacionalnost FROM Nationality");
                        DropDownListNationality.DataValueField = "idNacionalnost";
                        DropDownListNationality.DataTextField = "Nacionalnost";
                        DropDownListNationality.DataSource = Nacionalost;
                        DropDownListNationality.DataBind();
                        DropDownListNationality.Items.Insert(0, new ListItem("", ""));

                        DataSet Regions = ReturnDataSet.ReturSet("SELECT idRegion,region FROM Regions");
                        DropDownListRegion.DataValueField = "idRegion";
                        DropDownListRegion.DataTextField = "region";
                        DropDownListRegion.DataSource = Regions;
                        DropDownListRegion.DataBind();
                        DropDownListRegion.Items.Insert(0, new ListItem("", ""));

                        DataSet Locality = ReturnDataSet.ReturSet("SELECT idLocality,locality FROM Localitys");
                        DropDownListLocality.DataValueField = "idLocality";
                        DropDownListLocality.DataTextField = "locality";
                        DropDownListLocality.DataSource = Locality;
                        DropDownListLocality.DataBind();
                        DropDownListLocality.Items.Insert(0, new ListItem("", ""));

                        DataSet Income = ReturnDataSet.ReturSet("SELECT idIncome,opisIncome FROM Income");
                        DropDownListIncome.DataValueField = "idIncome";
                        DropDownListIncome.DataTextField = "opisIncome";
                        DropDownListIncome.DataSource = Income;
                        DropDownListIncome.DataBind();
                        DropDownListIncome.Items.Insert(0, new ListItem("", ""));
                        
                        
                        // Gi mestam izbranite opcii od DropDownlistite sprored tie na korisnikot vo baza
                        DropDownListSex.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[7].ToString()).Selected = true; 
                        DropDownListEducation.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[8].ToString()).Selected=true;
                        DropDownListRegion.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[9].ToString()).Selected=true;
                        DropDownListAge.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[10].ToString()).Selected=true;
                        DropDownListStructure.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[11].ToString()).Selected=true;
                        DropDownListNationality.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[12].ToString()).Selected=true;
                        DropDownListIncome.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[13].ToString()).Selected=true;
                        DropDownListLocality.Items.FindByValue(user.Tables["DataSet"].Rows[0].ItemArray[14].ToString()).Selected=true;
                    }                    
                    catch (Exception exception)
                    {
                        SendToLogFile.SendRecordToFIle(DateTime.Now.ToString() + " -exc- " + exception.Message.ToString() + " -stackTrace- " + exception.StackTrace.ToString() + " -AccountDetails- ");
                    }
                }
        }
        protected void saveButton_Click(object sender, EventArgs e)
        {
            try
            {
                String appPath = Request.PhysicalApplicationPath;
                String userName = UsernameTextBox.Text;
                String saveDir = @"Uploads\" + userName + "\\";
                String savePicPath = @"\Uploads\" + userName + "\\";

                System.IO.Directory.CreateDirectory(appPath + "Uploads\\" + userName);

                // AN gi zacuvuvam podatosite so izmenite
                Users.SaveChangesForUser(Int32.Parse(Session["idUser"].ToString()), FirstNameTextBox.Text, LastNameTextBox.Text, UsernameTextBox.Text, PasswordTextBox.Text, EMailTextBox.Text, QuestionTextBox.Text, AnswerTextBox.Text,
                    Int32.Parse(DropDownListSex.SelectedValue.ToString()),
                    Int32.Parse(DropDownListEducation.SelectedValue.ToString()),
                    Int32.Parse(DropDownListRegion.SelectedValue.ToString()),
                    Int32.Parse(DropDownListAge.SelectedValue.ToString()),
                    Int32.Parse(DropDownListStructure.SelectedValue.ToString()),
                    Int32.Parse(DropDownListNationality.SelectedValue.ToString()),
                    Int32.Parse(DropDownListIncome.SelectedValue.ToString()),
                    Int32.Parse(DropDownListLocality.SelectedValue.ToString())
                    , savePicPath);


                if (Session["MyCulture"].ToString() == "en-US")
                {
                    lblMessage.Text = "Changes were succefull";
                }
                else
                {
                    lblMessage.Text = "Промените се успешни.";
                }
                if (FileUpload1.HasFile)
                {
                    String fileName = Server.HtmlEncode(FileUpload1.FileName);
                    String extension = System.IO.Path.GetExtension(fileName);
                    int fileSize = FileUpload1.PostedFile.ContentLength;

                    if (fileSize < 2100000 && ((extension.ToUpper() == ".JPG") | (extension.ToUpper() == ".JPEG")))
                    {
                        // Patot i imeto na slikata vo Web aplikacijata
                        String savePath = appPath + saveDir + "profilePIC.jpg";
                        FileUpload1.SaveAs(savePath);

                        ImageManipulator.ResizeImage(savePath, savePath, 200, 200, false);
                    } 
                }
                else
                {
                    lblStatusUpload.Text = "You did not specify a file to upload.";
                }

            }
            catch (SqlException exception)
            {

                if (Session["MyCulture"].ToString() == "en-US")
                {
                    lblMessage.Text = "Changes were not succefull";
                }
                else
                {
                    lblMessage.Text = "Податоците не се успешно изменети";
                }
                
                SendToLogFile.SendRecordToFIle(DateTime.Now.ToString() + " -exc- " + exception.Message.ToString() + " -stackTrace- " + exception.StackTrace.ToString() + " -AccountDetails- saveButton_Click");
            }
            
        }
    }
}
